package xml;

import java.io.FileOutputStream;

import java.io.FileNotFoundException;
import java.io.IOException;

import javax.xml.stream.XMLOutputFactory;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamWriter;

public class MockVotingXMLWriter {
	
	FileOutputStream output;
	XMLOutputFactory factory = XMLOutputFactory.newInstance();
	XMLStreamWriter writer;
	
	public MockVotingXMLWriter(String fileName) throws FileNotFoundException, XMLStreamException {
		output = new FileOutputStream(fileName);
		writer = factory.createXMLStreamWriter(output);
	}

//------------------------------------------------------------------------------------------------------------------------
	
	private String hierarchyPoint = ""; //a String to hold the present level of indent.
	
	public void pushHierarchy() throws XMLStreamException {
		hierarchyPoint = hierarchyPoint + "    "; //push the indent right
	}
	
	public void pullHierarchy() throws XMLStreamException {
		hierarchyPoint = hierarchyPoint.substring(0, hierarchyPoint.length() - 4); //push the indent left
	}
	
	public void writeHierarchyPoint() throws XMLStreamException {
		writeChars(hierarchyPoint);
	}
	
//------------------------------------------------------------------------------------------------------------------------
	
	public void writeObject(Object o) throws XMLStreamException {
		writeHierarchyPoint();
		writeTag(o.getClass().getName(), o.toString());
		writeNewline();
	}

	public void writeChars(String s) throws XMLStreamException {
		writer.writeCharacters(s);
	}
	
	public void writeNewline() throws XMLStreamException {
		writeChars("\n");
	}
	
//------------------------------------------------------------------------------------------------------------------------
	
	public void writeStartElement(String tag) throws XMLStreamException {
		writeHierarchyPoint();
		writer.writeStartElement(tag);
	}
	
	public void writeEndElement() throws XMLStreamException {
		writeHierarchyPoint();
		writer.writeEndElement();
		writeNewline();
	}
	
	public void writeAttribute(String id, String val) throws XMLStreamException {
		writer.writeAttribute(id, val);
	}
	
	public void writeTag(String tag, String value) throws XMLStreamException {
		writeHierarchyPoint();
		writer.writeStartElement(tag);
		writer.writeCharacters(value);
		writer.writeEndElement();
		writeNewline();
	}
	
//------------------------------------------------------------------------------------------------------------------------
	
	public void writeComment(String comment) throws XMLStreamException {
		writer.writeComment(comment);
	}
	
	public void openDocument() throws XMLStreamException {
		writer.writeStartDocument();
		writeNewline();
	}
	
	public void closeDocument() throws IOException, XMLStreamException {
		writer.flush();
		writer.close();
		output.close();
	}
}